// 主界面
;
define(function(require, exports, module) {
	'use strict';
	var util = require("util");
	var base = require("base");
	var validate = require("validate");
	var lock = false;
	var css_news = require("./news_add.css");
	var databind = require("databind");
	var router = require("../hash/pageRouter");
	var newsCategoryIdDic = {
		enabled: 0,
		newsCategoryId: 0
	};
	var newsId;
	var images = [];
	var contents = [];
	var index = 0;
	var pageIndex = 1,
		pageSize = 1000,
		totalPageCount = 1,
		totalRecordCount = 0; //分页初始化
	var init = function(page) {
		if (page.params != null) {
			newsId = page.params.newsId;
		}
		initEvent();
		inquireNewsCategoryPageList();
	};
	var initEvent = function() {
		//若未登录，则返回登陆页面
		if (base.getData("sid") == null || base.getData("sid") == "" || base.getData("sid") == undefined) {
			top.location.href = "../login/login.html";
		}

		$("#main").on("click", "#news-add", function() {
			createNews();
		});

		$("#main").on("click", "#continue_add", function() {
			index = $(".newsItems").length + 1;
			var str = ['<div class="newsItems">',
				'			<input type="file" name="file" id="imageFile', index, '" class="none"/>',
				'			<label fileUuid="" for="imageFile', index, '" class="imageFile"></label>',
				'			<textarea class="newsContent"></textarea>',
				'			<div class="line"></div>',
				'		</div>'
			].join("");
			$(this).before(str);
			index++;
		});

		$("#main").on("change", ".newsItems input", function() {
			uploadPicture($(this).attr("id"));
		});

		$("#main").on("change", "#imageUuid", function() {
			uploadPicture("imageUuid");
		});
	};

	//上传图片
	var uploadPicture = function(fileElementId) {
		$.ajaxFileUpload({
			url: "/finance/api/v1.0/uploadFile.json", //你处理上传文件的服务端
			secureuri: false,
			fileElementId: fileElementId,
			dataType: 'json',
			success: function(data) {
				$("#" + fileElementId).parent().find("label").css("background", "url(/finance/api/v1.0/downloadFile.file?fileUuid=" + data.data[0].fileUuid + ")no-repeat");
				$("#" + fileElementId).parent().find("label").attr("fileUuid", data.data[0].fileUuid);
			},
			complete: function(xml) {},
			error: function(data, status, e) {
				if (data.msg == null) {
					base.alert(2, "文件太大无法上传");
				} else {
					base.alert(2, data.msg);
				}
			}
		});
	};

	// 获取资讯栏目
	var inquireNewsCategoryPageList = function() {
		base.fnAjax({
			action: "inquireCategoryPageList.json", //接口名称
			oData: {}, //传递参数
			fnSuccess: function(data) { //成功回调
				if (data.status == 200) {
					var tpl = $("#categoryTpl").html();
					var html = juicer(tpl, data);
					$("#newsCategoryBody").html(html);

					if (newsId != null) {
						inquireNewsDetail();
					}
				} else {
					base.alert(3, data.message);
				}
			}
		});
	};

	// 获取资讯明细
	var inquireNewsDetail = function() {
		base.fnAjax({
			action: "inquireNewsDetail.json", //接口名称
			oData: {
				newsId: newsId
			}, //传递参数
			fnSuccess: function(data) { //成功回调
				if (data.status == 200) {
					if (data.datas[0].imageUuid != "") {
						$("#imageUuidShort").parent().find("label").css("background", "url(/finance/api/v1.0/downloadFile.file?fileUuid=" + data.datas[0].imageUuid + ")no-repeat");
					}
					databind.fillForm($("#news_add"), data.datas[0]);
					if (data.datas[0].contents != "") {
						$(".newsItems").remove();
						$.each(data.datas[0].contents, function(i, v) {
							var str = ['<div class="newsItems">',
								'			<input type="file" name="file" id="imageFile', i, '" class="none"/>',
								'			<label fileUuid="', v.fileUuid, '" for="imageFile', i, '" class="imageFile"></label>',
								'			<textarea class="newsContent">', v.content, '</textarea>',
								'			<div class="line"></div>',
								'		</div>'
							].join("");
							$("#continue_add").before(str);
							$("#imageFile" + i).parent().find("label").css("background", "url(/finance/api/v1.0/downloadFile.file?fileUuid=" + v.fileUuid + ")no-repeat");
						});
					}
					databind.disableInput($("#news_add"));
					$("#continue_add").remove();
					$("#news_add .table-btn").html("返回").attr("href", "../news/news.html").removeAttr("id");
					
					if(data.datas[0].recommend=="true"){
						$("#news_add .table-btn:first").before('<a class="table-btn" style="margin-left: 50px;" id="cancelReommend">取消推荐</a>');
					}else{
						$("#news_add .table-btn:first").before('<a class="table-btn" style="margin-left: 50px;" id="recommend">推荐该新闻</a>');
					}

					$("#news_add").on("click", "#recommend", function() {
						recommendNews();
					});
					
					$("#news_add").on("click", "#cancelReommend", function() {
						disableRecommendNews();
					});
				} else {
					base.alert(3, data.message);
				}
			}
		});
	};

	//新增新闻
	var createNews = function() {
		var newsSourceLink = $("#newsSourceLink").val(); //原文链接
		var newsSource = $("#newsSource").val(); //资讯来源
		var imageUuid = $("#imageUuidShort").attr("fileuuid"); //资讯列表缩略图
		var recommend = $(".recommend:checked").val(); //是否推荐 推荐1
		var summary = $("#summary").val(); //资讯摘要
		var newsTitle = $("#newsTitle1").val(); //资讯标题
		var newsCategoryId = $("#newsCategoryBody").val(); //栏目ID
		var newsItems = $(".newsItems");

		for (var j = 0; j < newsItems.length; j++) {
			images.push($(newsItems[j]).find("label").attr("fileUuid"));
			contents.push($(newsItems[j]).find("textarea").val());
		}

		if (newsTitle.length <= 0) {
			base.alert(2, "资讯标题不能为空");
			return;
		}

		if (summary.length <= 0) {
			base.alert(2, "资讯摘要不能为空");
			return;
		}
		if (contents.length > 2000) {
			base.alert(2, "资讯内容长度不要超过2000个字符");
			return;
		}

		base.fnAjax({
			action: "createNews.json", //接口名称
			oData: {
				fileUuid: images,
				content: contents,
				newsSourceLink: newsSourceLink,
				newsSource: newsSource,
				imageUuid: imageUuid,
				recommend: recommend,
				summary: summary,
				newsTitle: newsTitle,
				newsCategoryId: newsCategoryId,
			}, //传递参数
			fnSuccess: function(data) { //成功回调
				if (data.status == 200) {
					base.alert(1, "添加成功！");
					base.openUrl("news.html");
				} else {
					base.alert(3, data.message);
				}
			}
		});
	}

	// 获取资讯栏目
	var inquireNewsCategoryPageList1 = function() {
		var html = function(data) {
			var str = "";
			for (var i = 0; i < data.datas.length; i++) {
				var row = data.datas[i];
				str += '<option value="' + row.newsCategoryId + '">' + row.categoryName + '</option>';
			}
			$("#newsCategoryId").append(str);
			if (newsCategoryIdDic.enabled == 1) {
				$("#newsCategoryId").val(newsCategoryIdDic.newsCategoryId);
			} else {
				newsCategoryIdDic.enabled = 1;
			};
		};
		base.fnAjax({
			action: "inquireNewsCategoryPageList.json", //接口名称
			oData: {
				categoryName: "",
				pageIndex: pageIndex,
				pageSize: pageSize
			}, //传递参数
			fnSuccess: function(data) { //成功回调
				if (data.status == 200) {
					html(data);
				} else {
					base.alert(3, data.message);
				}
			}
		});
	};

	// 推荐资讯
	var recommendNews = function() {
		base.fnAjax({
			action: "recommendNews.json", //接口名称
			oData: {
				newsId: newsId,
			}, //传递参数
			fnSuccess: function(data) { //成功回调
				if (data.status == 200) {
					base.alert(1, "推荐成功！");
					router.route("news/news_add.html?newsId="+newsId);
				} else {
					base.alert(3, data.message);
				}
			}
		});
	};

	// 取消推荐资讯
	var disableRecommendNews = function() {
		base.fnAjax({
			action: "disableRecommendNews.json", //接口名称
			oData: {
				newsId: newsId
			}, //传递参数
			fnSuccess: function(data) { //成功回调
				if (data.status == 200) {
					base.alert(1, "取消推荐成功！");
					router.route("news/news_add.html?newsId="+newsId);
				} else {
					base.alert(3, data.message);
				}
			}
		});
	};

	return {
		init: init
	};
});